﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Smrf.SocialNetworkLib;

namespace Smrf.NodeXL.GraphDataProviders.MediaWiki
{
    public partial class MediaWikiPageDialog : MediaWikiGraphDataProviderDialogBase
    {
        public MediaWikiPageDialog()
            :
            base(new MediaWikiPageNetworkAnalyzer())
        {
            InitializeComponent();
            addAttributes();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AssertValid();
            

        }


        //*************************************************************************
        //  Property: ToolStripStatusLabel
        //
        /// <summary>
        /// Gets the dialog's ToolStripStatusLabel control.
        /// </summary>
        ///
        /// <value>
        /// The dialog's ToolStripStatusLabel control, or null if the dialog
        /// doesn't have one.  The default is null.
        /// </value>
        ///
        /// <remarks>
        /// If the derived dialog overrides this property and returns a non-null
        /// ToolStripStatusLabel control, the control's text will automatically get
        /// updated when the HttpNetworkAnalyzer fires a ProgressChanged event.
        /// </remarks>
        //*************************************************************************

        protected override ToolStripStatusLabel
        ToolStripStatusLabel
        {
            get
            {
                AssertValid();

                return (this.slStatusLabel);
            }
        }

        //*************************************************************************
        //  Method: DoDataExchange()
        //
        /// <summary>
        /// Transfers data between the dialog's fields and its controls.
        /// </summary>
        ///
        /// <param name="bFromControls">
        /// true to transfer data from the dialog's controls to its fields, false
        /// for the other direction.
        /// </param>
        ///
        /// <returns>
        /// true if the transfer was successful.
        /// </returns>
        //*************************************************************************

        protected override Boolean
        DoDataExchange
        (
            Boolean bFromControls
        )
        {
            if (bFromControls)
            {
                // Validate the controls.

                

            
            }
            else
            {
           
            }

            return (true);
        }

        //*************************************************************************
        //  Method: StartAnalysis()
        //
        /// <summary>
        /// Starts the Flickr analysis.
        /// </summary>
        ///
        /// <remarks>
        /// It's assumed that DoDataExchange(true) was called and succeeded.
        /// </remarks>
        //*************************************************************************

        protected override void
        StartAnalysis()
        {
            AssertValid();

            m_oGraphMLXmlDocument = null;

            //Debug.Assert(m_oHttpNetworkAnalyzer is
            //    FlickrRelatedTagNetworkAnalyzer);

            //FlickrRelatedTagNetworkAnalyzer.WhatToInclude eWhatToInclude =

            //    (m_bIncludeSampleThumbnails ?
            //        FlickrRelatedTagNetworkAnalyzer.WhatToInclude.SampleThumbnails
            //        : 0)
            //    ;


            List<EdgeType> oEdgeTypes = new List<EdgeType>();
            int iNrOfRevisions = 0;
            DateTime oDownloadRevisionsFrom = DateTime.MinValue;

            if (chkHyperlinkCoauthorship.Checked)
            {
                oEdgeTypes.Add(EdgeType.HyperlinkCoauthorship);
            }
            if (chkCategoryCoauthorship.Checked)
            {
                oEdgeTypes.Add(EdgeType.CategoryCoauthorship);
            }

            if (rbDownloadByNr.Checked)
            {
                iNrOfRevisions = (int)nudRecentRevisions.Value;
            }
            else
            {
                oDownloadRevisionsFrom = dtRevisionsFrom.Value;
            }            

            try
            {
                ((MediaWikiPageNetworkAnalyzer)m_oHttpNetworkAnalyzer).
                GetNetworkAsync(txtWikiDomain.Text, txtSeedArticle.Text, attributes,
                                oEdgeTypes, iNrOfRevisions, oDownloadRevisionsFrom);
            }
            catch (NullReferenceException e)
            {
                MessageBox.Show(e.Message);
            }      
        
        }

        //*************************************************************************
        //  Method: EnableControls()
        //
        /// <summary>
        /// Enables or disables the dialog's controls.
        /// </summary>
        //*************************************************************************

        protected override void
        EnableControls()
        {
            AssertValid();

            Boolean bIsBusy = m_oHttpNetworkAnalyzer.IsBusy;

            //EnableControls(!bIsBusy, pnlUserInputs);
            //btnOK.Enabled = !bIsBusy;
            //this.UseWaitCursor = bIsBusy;
        }

        //*************************************************************************
        //  Method: OnEmptyGraph()
        //
        /// <summary>
        /// Handles the case where a graph was successfully obtained by is empty.
        /// </summary>
        //*************************************************************************

        protected override void
        OnEmptyGraph()
        {
            AssertValid();

            //this.ShowInformation("That tag has no related tags.");
            //txbTag.Focus();
        }

        //*************************************************************************
        //  Method: btnOK_Click()
        //
        /// <summary>
        /// Handles the Click event on the btnOK button.
        /// </summary>
        ///
        /// <param name="sender">
        /// Standard event argument.
        /// </param>
        ///
        /// <param name="e">
        /// Standard event argument.
        /// </param>
        //*************************************************************************

        protected void
        btnOK_Click
        (
            object sender,
            EventArgs e
        )
        {
            AssertValid();            
            readAttributes();
            OnOKClick();
        }


        //*************************************************************************
        //  Method: AssertValid()
        //
        /// <summary>
        /// Asserts if the object is in an invalid state.  Debug-only.
        /// </summary>
        //*************************************************************************

        // [Conditional("DEBUG")]

        public override void
        AssertValid()
        {
            base.AssertValid();

            //Debug.Assert(m_sTag != null);
            // m_eNetworkLevel
            // m_bIncludeSampleThumbnails
        }


        //*************************************************************************
        //  Protected constants
        //*************************************************************************

        /// Flickr Web page for requesting an API key.

        protected const String RequestFlickrApiKeyUrl =
            "http://www.flickr.com/services/api/misc.api_keys.html";


        //*************************************************************************
        //  Protected fields
        //*************************************************************************

        // These are static so that the dialog's controls will retain their values
        // between dialog invocations.  Most NodeXL dialogs persist control values
        // via ApplicationSettingsBase, but this plugin does not have access to
        // that and so it resorts to static fields.

        /// Tag to get the related tags for.  Can be empty but not null.

        protected static String m_sTag = "sociology";

        /// Network level to include.

        //protected static NetworkLevel m_eNetworkLevel = NetworkLevel.OnePointFive;

        /// true to include a sample thumbnail for each tag.

        protected static Boolean m_bIncludeSampleThumbnails = false;

        public String sCookieContent;
        private MediaWikiLoginDialog o_fcbLoginDialog;

        private Dictionary<string, JSONObject> forumData, selectedForumData, threadData, selectedThreadData;

        private WhatToDownload m_eWhatToDownload = WhatToDownload.All;
        private List<EdgeType> oEdgeTypes = new List<EdgeType>();

        private Dictionary<Attribute, bool> attributes = new Dictionary<Attribute,bool>() 
        {
            {new Attribute("Name","Name"),true},            
            //{new Attribute("Editor Type","EditorType"),true},
            //{new Attribute("Article Type","ArticleType"),true},
            {new Attribute("Editor Edits","editcount"),true},
            {new Attribute("Editor Block Info","blockinfo"),false},
            {new Attribute("Editor Registration Date","registration"),true},
            {new Attribute("Editor Gender","gender"),true},
            //{new Attribute("Article Gini Coefficient","ArticleGiniCoefficient"),false},
            //{new Attribute("Article Age","ArticleAge"),false},
            //{new Attribute("Editor Revisions","EditorRevisions"),false},
            //{new Attribute("Editor Gini Coefficient","EditorGiniCoefficient"),false},
            //{new Attribute("Editor Age","EditorAge"),false}
        };  

        private void addAttributes()
        {
            int i = 0;
            dgAttributes.Rows.Add(attributes.Count);            
            foreach (KeyValuePair<Attribute, bool> kvp in attributes)
            {
                dgAttributes.Rows[i].Cells[0].Value = kvp.Key.name;
                dgAttributes.Rows[i].Cells[1].Value = kvp.Value;                
                dgAttributes.Rows[i].Cells[2].Value = kvp.Key.value;                
                i++;
            }
        }


        private void button1_Click_1(object sender, EventArgs e)
        {            
            readAttributes();
            //o_fcbLoginDialog = new MediaWikiLoginDialog(this, txtHost.Text);
            //o_fcbLoginDialog.LogIn();
            sCookieContent = o_fcbLoginDialog.CookieContent;
        }

        
        public struct Attribute
        {
            public string name, value;

            public Attribute(string name, string value)
            {
                this.name = name;
                this.value = value;
            }
        }
        

        private void PrintAttributes()
        {
            string text = "";
            foreach (KeyValuePair<Attribute, bool> kvp in attributes)
            {
                text += kvp.Key.name + "=" + kvp.Value.ToString() + "\n";
            }

            this.ShowInformation(text);
        }

        private void readAttributes()
        {
            foreach (DataGridViewRow row in dgAttributes.Rows)
            {
                attributes[new Attribute(row.Cells[0].Value.ToString(),
                row.Cells[2].Value.ToString())] = (Boolean)row.Cells[1].Value;
            }
            //PrintAttributes();
        }

        private string createRequiredPermissionsString()
        {
            return String.Empty;            
        }

        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dgAttributes.Rows)
            {
                row.Cells[1].Value = ((CheckBox)sender).Checked;
            }
        }

        private void MediaWikiPageDialog_Load(object sender, EventArgs e)
        {
            dgAttributes.Columns[1].Width = 
                TextRenderer.MeasureText(dgAttributes.Columns[1].HeaderText,
                dgAttributes.Columns[1].HeaderCell.Style.Font).Width + 25;
            //Get the column header cell bounds

            Rectangle rect =
                this.dgAttributes.GetCellDisplayRectangle(1, -1, true);           

            //Change the location of the CheckBox to make it stay on the header

            chkSelectAll.Location = 
                new Point(rect.Location.X + rect.Width - 20,
                    rect.Location.Y + Math.Abs((rect.Height - chkSelectAll.Height)/2));

            chkSelectAll.CheckedChanged += new EventHandler(chkSelectAll_CheckedChanged);

            //Add the CheckBox into the DataGridView

            this.dgAttributes.Controls.Add(chkSelectAll);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //if (o_fcbLoginDialog == null)
            //    o_fcbLoginDialog = new MediaWikiLoginDialog(this, txtHost.Text);

            //o_fcbLoginDialog.Text = Host;
            o_fcbLoginDialog.LogOut();
        }

        public MediaWikiLoginDialog FacebookLoginDialog
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
            }
        }

        public MediaWikiPageNetworkAnalyzer sdcsd
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
            }
        }    

       

        
    }
}
